#include "Acceptor.h"

Acceptor::Acceptor(EventLoop* loop, const char *ip, uint16_t port) 
    : m_loop(loop),m_servsock(create_nonblocking()),m_acceptchannel(m_loop, m_servsock.fd())
{
    InetAddress servaddr(ip, port);
    //这里要用堆对象，因为析构函数会关闭fd，如果是栈对象，出了作用域就会关闭fd
    //m_servsock = new Socket(create_nonblocking());
    m_servsock.set_reuseaddr(true);
    m_servsock.set_reuseport(true);
    m_servsock.set_tcpnodelay(true);
    m_servsock.set_keepalive(true);
    m_servsock.bind(servaddr);
    m_servsock.listen();

    //m_acceptchannel = new Channel(m_loop, m_servsock.fd());
    m_acceptchannel.set_read_callback(std::bind(&Acceptor::new_connection, this));
    m_acceptchannel.enable_reading();
}

Acceptor::~Acceptor()
{
}

void Acceptor::new_connection()
{
    InetAddress clientaddr;
    std::unique_ptr<Socket> clientsock(new Socket(m_servsock.accept(clientaddr)));
    clientsock->set_ip_port(clientaddr.ip(),clientaddr.port());
    
    m_new_conneciton_cb(std::move(clientsock));
}

void Acceptor::set_callback(std::function<void(std::unique_ptr<Socket>)> fn)
{
    m_new_conneciton_cb = fn;
}